const express = require('express');
const router = express.Router();
const Department = require('../models/department');

// 创建部门
router.post("/department", async (req, res) => {
  //使用Hero model上的create方法储存数据
  try {
    const department = new Department(req.body)
    await department.save();
    res.send({ message: "操作成功" })
  } catch (err) {
    // 如果有错误，返回错误信息  
    res.status(500).json({ error: err.message });
  }
});
// 查询部门
router.get("/department", async (req, res) => {
  try {
    const { deptName, status } = req.query;
    const query = {};
    if (deptName) query.deptName = deptName;
    if (status) query.status = status;
    const department = await Department.find(query);
    res.send({ data: department, code: 200, message: "查询成功" });
  } catch (err) {
    res.status(500).send({ error: err });
  }
});
// 编辑部门
router.put("/department", async (req, res) => {
   try {
      const updatedDepartment = await Department.findByIdAndUpdate(req.body.id, req.body, { new: true });
      if (!updatedDepartment) return res.status(404).send({ error: 'Hero not found' });
      res.send({message:"操作成功"});
    } catch (err) {
      res.status(500).send({ error: 'Failed to update hero' });
    }
});
//删除部门
router.delete("/department", async (req, res) => {
  try {
    // 从查询参数中获取id
    const departmentId = req.query.id;
    if (!departmentId) {
      return res.status(400).send({ error: 'Missing "id" query parameter' });
    }

    await Department.findByIdAndDelete(departmentId);
    res.send({ message: '操作成功' });
  } catch (err) {
    if (err.name === 'CastError') return res.status(404).send({ error: 'Hero not found' });
    res.status(500).send({ error: '操作失败' });
  }
});
module.exports = router